package com.sanjiayi.utils;

import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeAllTextRequest;
import com.aliyun.ocr_api20210707.models.RecognizeAllTextResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云OCR图片识别工具类
 */
public class AliyunOCRUtil {

    // 客户端实例，使用静态变量避免重复创建
    private static Client client;

    // 初始化客户端
    static {
        try {
            client = createClient();
        } catch (Exception e) {
            throw new RuntimeException("初始化阿里云OCR客户端失败", e);
        }
    }

    /**
     * 创建OCR客户端
     */
    private static Client createClient() throws Exception {
        Config config = new Config()
                // 必填，请确保代码运行环境设置了环境变量
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 识别图片中的文字
     * @param imageUrl 图片URL
     * @param type 识别类型，如IdCard、BusinessLicense等
     * @return 识别结果JSON字符串
     * @throws Exception 异常信息
     */
    public static String recognizeText(String imageUrl, String type) throws Exception {
        if (imageUrl == null || imageUrl.isEmpty()) {
            throw new IllegalArgumentException("图片URL不能为空");
        }
        if (type == null || type.isEmpty()) {
            throw new IllegalArgumentException("识别类型不能为空");
        }

        RecognizeAllTextRequest request = new RecognizeAllTextRequest()
                .setUrl(imageUrl)
                .setType(type);

        RuntimeOptions runtime = new RuntimeOptions();

        try {
            RecognizeAllTextResponse response = client.recognizeAllTextWithOptions(request, runtime);
            return com.aliyun.teautil.Common.toJSONString(response.body.data);
        } catch (TeaException error) {
            // 记录详细错误信息
            Map<String, Object> errorInfo = new HashMap<>();
            errorInfo.put("code", error.code);
            errorInfo.put("message", error.message);
            errorInfo.put("data", error.getData());
            errorInfo.put("recommend", error.getData().get("Recommend"));

            throw new Exception("OCR识别失败: " + com.aliyun.teautil.Common.toJSONString(errorInfo), error);
        } catch (Exception e) {
            throw new Exception("调用OCR服务发生未知错误", e);
        }
    }

    /**
     * 设置自定义配置（用于测试或特殊场景）
     */
    public static void setCustomClient(Client customClient) {
        AliyunOCRUtil.client = customClient;
    }
}
